package com.promise.jokerdream.work.manager

import com.promise.jokerdream.work.BaseWorkManager
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.utils.AppContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.time.LocalDateTime

/**
 * 通用工作管理器
 * 负责执行普通的一键代玩任务
 */
class CommonWorkManager : BaseWorkManager() {

    companion object {
        @Volatile
        private var INSTANCE: CommonWorkManager? = null

        /**
         * 获取CommonWorkManager单例
         */
        fun getInstance(): CommonWorkManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: CommonWorkManager().also { INSTANCE = it }
            }
        }
    }

    // 用户数据管理器，用于更新用户配置
    private val userDataManager by lazy { UserDataManager.getInstance(AppContext.get()) }

    override fun getManagerName(): String {
        return "代玩"
    }

    /**
     * 执行完成后更新 lastHourlyWorkExecutedTime
     */
    override suspend fun onExecutionCompleted() {
        try {
            withContext(Dispatchers.IO) {
                val currentAccount = userDataManager.getCurrentAccount()
                if (currentAccount != null) {
                    val now = LocalDateTime.now()
                    val updatedConfig = currentAccount.config.copy(
                        lastHourlyWorkExecutedTime = now.toString()
                    )
                    val updatedAccount = currentAccount.copy(config = updatedConfig)
                    userDataManager.saveUserAccount(updatedAccount)
                    println("CommonWorkManager执行完成，已更新lastHourlyWorkExecutedTime: ${now}")
                }
            }
        } catch (e: Exception) {
            println("更新lastHourlyWorkExecutedTime失败: ${e.message}")
            e.printStackTrace()
        }
    }
}